import watcher from "./observer/watcher";
import { patch } from "./vnode/patch";

export function mountComponent (vm, el) {
  // vm._render 将render函数变成vnode
  // vm._update 将vnode变成真是DOm，在放到页面上
  callHook(vm, 'beforeMount')
  let updateComponent = () => {
    vm._update(vm._render())
  }
  new watcher(vm, updateComponent, () => {
    callHook(vm, 'updated')
  }, true)
  callHook(vm, 'mounted')
}

export function lifecycleMixin (Vue) {
  Vue.prototype._update = function (vnode) {
    // console.log('vnode===', vnode);
    let vm = this;
    // 两个参数 旧的dom和vnode
    vm.$el = patch(vm.$el, vnode);
  }
}

// 生命周期调用
export function callHook (vm, hook) {
  const handlers = vm.$options[hook];
  if (handlers) {
    for (let i = 0; i < handlers.length; i ++) {
      // 改变生命周期this的指向
      handlers[i].call(this)
    }
  }
}